<template>
	<view class="page">
		<view class="header">
			<image class="header-back-icon" src="/static/images/common/back.png" @click="pageBack"></image>
			<text class="header-title">搜索页</text>
		</view>
		
		<view class="search-bar">
			<input class="search-input" placeholder="请输入商家或商品名称" v-model="to_query" @keydown.enter="test" />
			<text class="search-btn" @click="test">搜索</text>
		</view>
		
		<view class="body">
			<view class="search-advice"></view>
			<text class="tag-title" v-show="isNotSearch">热门搜索</text>
			<view class="tag-container" v-show="isNotSearch">
				<text class="tag" v-for="item in tags">{{ item }}</text>
			</view>
			
			<view class="search-content" v-show="!isNotSearch">
				<view class="search-result-item" 
					v-for="query_item in query_results" 
					@click="handleClickQuery(query_item.shop_id)">
					<image class="search-icon" src="/static/images/index/searchIcon.png"></image>
					<text>{{ query_item.shop_name || query_item.dish_name }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { onMounted, reactive, ref, toRaw, watch } from 'vue';
	import { pageBack } from '/utils/main';
	import { httpGet } from '@/utils/request';
	import * as main from "@/static/scripts/search.js"
	// variables
	const tags = [
		"西大锅盔", "青楠五味茶", "粥咸鸭蛋", "一次性烧烤纸", "一之螺", 		
		"麻辣鸡", "夫妻肺片", "垃圾桶", "除湿袋干燥剂", "鳗鱼饭",
		"肉饼", "烧水壶", "雨伞", "东北麻辣烫", "芥末"
	]
	 
	const shops_data = reactive([])
	const dishes_data = reactive([])
	const shop_dish = reactive([])
	
	const isNotSearch = ref(true)
	const to_query = ref("")
	const query_results = reactive([])
	
	function fetchData() {
		httpGet("/api/get_to_search")
		.then((res) => {
			main.listCopy(shops_data, res.data.data.shops)
			main.listCopy(dishes_data, res.data.data.dishes)
			main.listCopy(shop_dish, res.data.data.shop_dish)
			
			console.log("shops_data:", shops_data)
			console.log("dishes_data:", dishes_data)
			console.log("shop_dish:", shop_dish)
		})
		.catch((err) => {
			main.listCopy(shops_data, ['none'])
			main.listCopy(dishes_data, ['none'])
			main.listCopy(shop_dish, ['none'])
		})
		
	}
	
	onMounted(() => {
		fetchData() // TODO 一开始加载页面就开始加载数据了。而不是要用到数据时才加载
	})
	watch(to_query, (_to_query) => {
		main.listCopy(query_results, main.blurQuery(_to_query, shops_data, dishes_data, shop_dish))
		if (to_query.value) isNotSearch.value = false
		else isNotSearch.value = true
	})
	
	function handleClickQuery(_shop_id) {
		console.log("go to shop: ", _shop_id)
		uni.navigateTo({
			url: `/pages/shop/shop?shop_id=${_shop_id}`
		})
	}
	
	function test() {
		console.log("yes")
	}
	
</script>

<style lang="scss">
	@import "@/static/styles/base/page.scss";
	@import "@/static/styles/base/header.scss";
	@import "@/static/styles/search/search.scss";
</style>
